<template>
	<view class="mine-page" :style="{ paddingTop: statusBarHeight + 'px' }">
		<!-- 未登录状态 -->
		<view v-if="!isLogin" class="login-prompt">
			<view class="login-card">
				<text class="login-title">欢迎使用萌宠管家</text>
				<text class="login-subtitle">请登录以享受完整功能</text>
				<button class="login-btn" @tap="handleWxLogin">
					<text class="btn-icon">📱</text>
					<text class="btn-text">微信一键登录</text>
				</button>
				<!-- 添加一个单独的按钮用于获取用户信息 -->
				<button v-if="hasLoginCode" class="get-userinfo-btn" @tap="handleGetUserProfile">
					<text class="btn-text">点击授权获取用户信息</text>
				</button>
			</view>
		</view>

		<!-- 已登录状态 -->
		<view v-else>
			<!-- 用户信息卡片 -->
			<view class="user-card" @tap="goToEditProfile">
				<view class="user-header">
					<image :src="userInfo.avatarUrl || '/static/images/user-avatar.png'" mode="aspectFill"
						class="user-avatar"></image>
					<view class="user-info">
						<text class="username">{{ userInfo.nickName || '铲屎官' }}</text>
						<text class="user-id">ID: {{ userInfo.id || '88888888' }}</text>
					</view>
					<view class="vip-badge">
						<text class="badge-text">VIP</text>
					</view>
				</view>
			</view>

			<!-- 健康评分和积分 -->
			<view class="stats-card">
				<view class="stat-item">
					<text class="stat-label">宠物健康评分</text>
					<view class="score-row">
						<text class="score-value">{{ userInfo.healthScore }}</text>
						<text class="score-change">+3分</text>
					</view>
					<view class="progress-bar">
						<view class="progress-fill" style="width: 92%"></view>
					</view>
					<text class="stat-tip">较上月提升3分，继续保持！</text>
				</view>

				<view class="divider"></view>

				<view class="stat-item">
					<text class="stat-label">我的积分</text>
					<view class="points-row">
						<text class="points-value">{{ userInfo.points }}</text>
						<text class="points-unit">积分</text>
					</view>
					<view class="points-btn" @tap="goToPointsMall">
						<text class="btn-text" style="color: black;">积分商城</text>
					</view>
				</view>
			</view>

			<!-- 我的宠物 -->
			<view class="my-pets-section">
				<view class="section-header">
					<text class="section-title">我的宠物</text>
					<view class="add-pet-btn" @tap="addPet()">
						<text class="iconfont">+</text>
					</view>
				</view>
				<scroll-view scroll-x class="pets-scroll">
					<view class="pets-list">
						<view class="pet-item" v-for="(item, index) in myPets" :key="item.petId" @tap="viewPetDetail(item.petId)">
							<image :src="item.avatar" mode="aspectFill" class="pet-avatar"></image>
							<text class="pet-name">{{ item.name }}</text>
						</view>
					</view>
				</scroll-view>
			</view>

			<!-- 功能菜单 -->
			<view class="menu-section">
				<view class="menu-item" v-for="(item, index) in menuItems" :key="index" @tap="handleMenuItem(item)">
					<view class="menu-icon" :style="{backgroundColor: item.bgColor}">
						<text class="icon-text">{{ item.icon }}</text>
					</view>
					<text class="menu-text">{{ item.text }}</text>
					<text class="menu-arrow">→</text>
				</view>
			</view>

			<!-- 服务推荐 -->
			<view class="services-section">
				<view class="section-header">
					<text class="section-title">推荐服务</text>
				</view>
				<view class="services-grid">
					<view class="service-card" v-for="(service, index) in services" :key="index">
						<view class="service-icon" :style="{backgroundColor: service.bgColor}">
							<text class="icon-text">{{ service.icon }}</text>
						</view>
						<text class="service-name">{{ service.name }}</text>
						<text class="service-desc">{{ service.desc }}</text>
						<view class="service-btn">
							<text class="btn-text" style="color: black;">查看详情</text>
						</view>
					</view>
				</view>
			</view>

			<!-- 退出登录按钮 -->
			<view class="logout-section">
				<button class="logout-btn" @tap="handleLogout">退出登录</button>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		onUnmounted
	} from 'vue'
	import { onShow } from '@dcloudio/uni-app'; // 单独导入 onShow（关键修正）
	import userManager from '../../common/utils/user.js'
	import systemUtils from '../../common/utils/system.js'
	import {LoginApi} from '@/api/Loginapi.js'
	import petApi from '@/api/pet.js'
	const statusBarHeight = ref(0)
	const isLogin = ref(false)
	const userInfo = ref({})
	const hasLoginCode = ref(false) // 标记是否已获取登录凭证
	const userId = ref(userManager.getUserInfo()?.userId || '');//登录后的id
	const myPets = ref([])//我的宠物列表
	const ownerId=ref('')//宠物主人id

	const menuItems = [{
			icon: '📋',
			text: '我的订单',
			bgColor: '#89CFF020',
			action: 'orders'
		},
		{
			icon: '❤️',
			text: '我的收藏',
			bgColor: '#FFD1DC20',
			action: 'favorites'
		},
		{
		        icon: '🛒', // 购物车图标
		        text: '购物车',
		        bgColor: '#B7F0AD20',
		        action: 'cart' // 新增 action 用于跳转
		    },
		{
			icon: '🏠',
			text: '收货地址',
			bgColor: '#B7F0AD20',
			action: 'address'
		},
		{
			icon: '👥',
			text: '我的好友',
			bgColor: '#89CFF020',
			action: 'friends'
		},
		{
			icon: '⚙️',
			text: '我的帖子',
			bgColor: '#FFD1DC20',
			action: 'mypost'
		}
	]

	const services = [{
			icon: '🏥',
			name: '健康管理服务',
			desc: '定期体检、疫苗提醒和健康评估',
			bgColor: '#FFD1DC20'
		},
		{
			icon: '🏠',
			name: '宠物寄养服务',
			desc: '专业人员照顾，实时查看宠物状况',
			bgColor: '#89CFF020'
		}
	]

	// 页面加载时获取状态栏高度并检查登录状态
	onMounted(() => {
		statusBarHeight.value = systemUtils.getStatusBarHeight()
		
		// 检查登录状态（会同步验证本地存储）
		isLogin.value = userManager.checkLogin()
		
		if (isLogin.value) {
			// 注意：统一使用小写的 'user_info'
			userInfo.value = uni.getStorageSync('user_info') || userManager.getUserInfo()
			
			// 补充：已登录状态下进入页面，拉取宠物列表
			if (userInfo.value) {
				userId.value = userInfo.value.userId || userManager.getUserInfo()?.userId
				getPet()
			}
		} else {
			// 未登录时清空用户信息
			userInfo.value = {}
			userId.value = ''
		}
		
        console.log('登录状态:', isLogin.value, '用户信息:', userInfo.value)
		
		// 监听登录状态变化
		uni.$on('loginStatusChanged', handleLoginStatusChanged)
	})
	
	// 页面显示时触发（包括从添加宠物页面返回）
onShow(() => {
  // 只有已登录且 userId 存在时，才刷新宠物列表
  if (userId.value) {
    getPet();
  }
});

	// 组件卸载时取消监听
	onUnmounted(() => {
		uni.$off('loginStatusChanged', handleLoginStatusChanged)
	})

	// 处理登录状态变化
	const handleLoginStatusChanged = (loginStatus) => {
		isLogin.value = loginStatus
		if (loginStatus) {
			userInfo.value = userManager.getUserInfo()
		} else {
			userInfo.value = {}
			hasLoginCode.value = false
		}
	}

	const handleWxLogin = async () => {
		try {
			// 第一步：获取登录凭证
			await userManager.wxLogin()
			hasLoginCode.value = true

			uni.showToast({
				title: '登录凭证获取成功，请点击下方按钮授权',
				icon: 'none',
				duration: 3000
			})
		} catch (err) {
			console.error('登录失败', err)
			uni.showToast({
				title: '登录失败，请重试',
				icon: 'none'
			})
		}
	}

	const handleGetUserProfile = async () => {
		try {
			// 第二步：获取用户信息（必须由用户主动点击触发）
			const userInfoData = await userManager.getUserProfile()

			isLogin.value = true
			userInfo.value = userInfoData
			hasLoginCode.value = false

			uni.showToast({
				title: '登录成功',
				icon: 'success'
			})
			
			    
			
			//登录成功后，立即调用 getPet 获取当前用户的宠物列表
			await getPet();
			
			// 为后续后端登录功能预留用户信息
			console.log('用户登录信息已保存，可用于后端验证:', userInfoData)

			// 触发登录状态变化事件，确保其他页面也能收到通知
			uni.$emit('loginStatusChanged', true)
		} catch (err) {
			console.error('获取用户信息失败', err)
			uni.showToast({
				title: '获取用户信息失败，请重试',
				icon: 'none'
			})
			// 确保登录状态为false
			isLogin.value = false
			userInfo.value = {}
			hasLoginCode.value = false
		}
	}
	
const getPet = async () => {
  try {
	  myPets.value = []; // 清空旧数据，触发重新渲染
	  const ownerRes = await petApi.getPetOwnerIdByUserId();
	  if (ownerRes.data.code === 200) {
	    ownerId.value = ownerRes.data.data; // 存储ownerId
	    console.log('获取到的ownerId:', ownerId.value);
	  } else {
	    uni.showToast({ title: '获取主人ID失败', icon: 'none' });
	  }
	  
    const petInfoData = await petApi.getPetsByUserId()
    console.log("获取到的宠物信息：", petInfoData);
	if(petInfoData.data.code==200){
		// 将获取到的宠物数据赋值给 myPets，页面才会渲染
		myPets.value = petInfoData.data.data;
	}
    
  } catch (err) {
    console.log("获取宠物信息失败", err);
    uni.showToast({
      title: '获取宠物信息失败，请重试',
      icon: 'none'
    })
  }
}

	const handleLogout = () => {
		// 调用 userManager 的 logout 方法
		userManager.logout()
		
		// 清空页面状态
		isLogin.value = false
		userInfo.value = {}
		userId.value = ''
		myPets.value = []
		hasLoginCode.value = false
		
		// Toast 提示已在 userManager.logout() 中处理
	}

	const goToPointsMall = () => {
		uni.showToast({
			title: '积分商城',
			icon: 'none'
		})
	}

	const addPet = () => {
	  if (!ownerId.value) {
	    uni.showToast({ title: '未获取到主人ID，无法添加宠物', icon: 'none' });
	    return;
	  }
	  // 关键步骤：通过url参数传递ownerId
	  uni.navigateTo({
	    url: `/pages/add-pet/add-pet?ownerId=${ownerId.value}`
	  });
	};
//跳转到宠物详情页面
	const viewPetDetail = (petId) => {
		uni.navigateTo({
			url: '/pages/pet-detail/pet-detail?id=' + petId
		})
	}

	const handleMenuItem = (item) => {
		switch(item.action) {
		        case 'orders':
		            uni.navigateTo({
		                url: `/pages/orders/orders`
		            })
		            break
		        case 'favorites':
		            uni.navigateTo({
		                url: `/pages/favorites/favorites`
		            })
		            break
		        case 'cart':
		            uni.navigateTo({
		                url: '/pages/cart/cart'
		            })
		            break
		        case 'address':
		            uni.navigateTo({
		                url: '/pages/address/address'
		            })
		            break
		        case 'friends':
		            uni.navigateTo({
		                url: '/pages/friends/friends'
		            })
		            break
		        case 'mypost':
					  uni.navigateTo({
					    url: `/pages/post-detail/my-post/my-post`
					  })
		            break
		        default:
		            uni.showToast({ title: item.text, icon: 'none' })
		    }
	}

	// 跳转到编辑用户信息页面
	const goToEditProfile = () => {
		if (!isLogin.value) {
			uni.showToast({ title: '请先登录', icon: 'none' })
			return
		}
		uni.navigateTo({
			url: '/pages/user-edit/user-edit'
		})
	}
</script>

<style scoped>
	.mine-page {
		min-height: 100vh;
		background-color: #F5F5F5;
		padding-bottom: 120rpx;
	}

	/* 登录提示 */
	.login-prompt {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100vh;
		padding: 32rpx;
	}

	.login-card {
		background-color: #FFFFFF;
		border-radius: 24rpx;
		padding: 64rpx 48rpx;
		text-align: center;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		width: 100%;
	}

	.login-title {
		font-size: 36rpx;
		font-weight: bold;
		color: #333333;
		display: block;
		margin-bottom: 16rpx;
	}

	.login-subtitle {
		font-size: 28rpx;
		color: #999999;
		display: block;
		margin-bottom: 48rpx;
	}

	.login-btn {
		background: linear-gradient(135deg, #89CFF0 0%, #B7F0AD 100%);
		border: none;
		border-radius: 999rpx;
		padding: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 16rpx;
		width: 100%;
		margin-bottom: 32rpx;
	}

	.get-userinfo-btn {
		background-color: #FFD1DC;
		border: none;
		border-radius: 999rpx;
		padding: 24rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 16rpx;
		width: 100%;
	}

	.btn-icon {
		font-size: 36rpx;
	}

	.btn-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #ffffff;
	}

	.get-userinfo-btn .btn-text {
		color: #333333;
	}

	/* 用户信息卡片 */
	.user-card {
		background: linear-gradient(135deg, #89CFF0 0%, #B7F0AD 100%);
		padding: 48rpx 32rpx;
		margin-bottom: 24rpx;
	}

	.user-header {
		display: flex;
		align-items: center;
	}

	.user-avatar {
		width: 128rpx;
		height: 128rpx;
		border-radius: 50%;
		border: 4rpx solid rgba(255, 255, 255, 0.5);
		margin-right: 24rpx;
	}

	.user-info {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.username {
		font-size: 36rpx;
		font-weight: bold;
		color: #FFFFFF;
		margin-bottom: 8rpx;
	}

	.user-id {
		font-size: 24rpx;
		color: rgba(255, 255, 255, 0.8);
	}

	.vip-badge {
		background: linear-gradient(135deg, #FFD700, #FFA500);
		padding: 12rpx 24rpx;
		border-radius: 999rpx;
	}

	.badge-text {
		font-size: 24rpx;
		font-weight: bold;
		color: #FFFFFF;
	}

	/* 统计卡片 */
	.stats-card {
		background-color: #FFFFFF;
		border-radius: 24rpx;
		padding: 32rpx;
		margin: 0 32rpx 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		display: flex;
	}

	.stat-item {
		flex: 1;
		display: flex;
		flex-direction: column;
	}

	.divider {
		width: 1px;
		background-color: #F0F0F0;
		margin: 0 32rpx;
	}

	.stat-label {
		font-size: 24rpx;
		color: #999999;
		margin-bottom: 16rpx;
	}

	.score-row {
		display: flex;
		align-items: baseline;
		margin-bottom: 16rpx;
	}

	.score-value {
		font-size: 60rpx;
		font-weight: bold;
		color: #89CFF0;
		margin-right: 16rpx;
	}

	.score-change {
		font-size: 24rpx;
		color: #00C853;
	}

	.progress-bar {
		width: 100%;
		height: 8rpx;
		background-color: #F0F0F0;
		border-radius: 999rpx;
		overflow: hidden;
		margin-bottom: 12rpx;
	}

	.progress-fill {
		height: 100%;
		background-color: #89CFF0;
		border-radius: 999rpx;
	}

	.stat-tip {
		font-size: 20rpx;
		color: #999999;
	}

	.points-row {
		display: flex;
		align-items: baseline;
		margin-bottom: 16rpx;
	}

	.points-value {
		font-size: 60rpx;
		font-weight: bold;
		color: #B7F0AD;
		margin-right: 8rpx;
	}

	.points-unit {
		font-size: 24rpx;
		color: #999999;
	}

	.points-btn {
		background-color: #89CFF020;
		color: #89CFF0;
		padding: 12rpx 24rpx;
		border-radius: 999rpx;
		font-size: 24rpx;
		align-self: flex-start;
	}

	/* 我的宠物 */
	.my-pets-section {
		background-color: #FFFFFF;
		border-radius: 24rpx;
		padding: 32rpx;
		margin: 0 32rpx 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	}

	.section-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 24rpx;
	}

	.section-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333333;
	}

	.add-pet-btn {
		width: 48rpx;
		height: 48rpx;
		border-radius: 50%;
		background-color: #89CFF0;
		color: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 32rpx;
	}

	.pets-scroll {
		width: 100%;
		white-space: nowrap;
		padding-bottom: 8rpx; /* 增加底部内边距，防止裁剪 */
		overflow-x: auto; /* 强制显示横向滚动条（可选，增强提示） */
	}

	.pets-list {
	  display: flex; /* 替换 inline-flex */
	  gap: 24rpx;
	  flex-wrap: nowrap; /* 强制不换行，确保横向滚动 */
	  padding: 4rpx 0; /* 增加上下内边距，优化触摸体验 */
	}

	.pet-item {
	  display: flex;
	  flex-direction: column;
	  align-items: center;
	  min-width: 140rpx; /* 给每个宠物项设置最小宽度，避免挤压 */
	}
	
	.pet-avatar {
	  width: 128rpx;
	  height: 128rpx;
	  border-radius: 50%;
	  border: 4rpx solid #89CFF0;
	  margin-bottom: 12rpx;
	  object-fit: cover; /* 确保图片填充不拉伸 */
	}

	.pet-name {
		font-size: 24rpx;
		color: #333333;
	}

	/* 功能菜单 */
	.menu-section {
		background-color: #FFFFFF;
		border-radius: 24rpx;
		padding: 16rpx 32rpx;
		margin: 0 32rpx 24rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	}

	.menu-item {
		display: flex;
		align-items: center;
		padding: 24rpx 0;
		border-bottom: 1px solid #F0F0F0;
	}

	.menu-item:last-child {
		border-bottom: none;
	}

	.menu-icon {
		width: 72rpx;
		height: 72rpx;
		border-radius: 16rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 24rpx;
		font-size: 36rpx;
	}

	.menu-text {
		flex: 1;
		font-size: 28rpx;
		color: #333333;
	}

	.menu-arrow {
		font-size: 28rpx;
		color: #999999;
	}

	/* 服务推荐 */
	.services-section {
		padding: 0 32rpx;
	}

	.services-grid {
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		gap: 24rpx;
	}

	.service-card {
		background-color: #FFFFFF;
		border-radius: 24rpx;
		padding: 32rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
	}

	.service-icon {
		width: 96rpx;
		height: 96rpx;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 48rpx;
		margin-bottom: 16rpx;
	}

	.service-name {
		font-size: 28rpx;
		font-weight: 500;
		color: #333333;
		margin-bottom: 8rpx;
		text-align: center;
	}

	.service-desc {
		font-size: 20rpx;
		color: #999999;
		text-align: center;
		line-height: 1.4;
		margin-bottom: 16rpx;
	}

	.service-btn {
		border: 1px solid #89CFF0;
		color: #89CFF0;
		padding: 12rpx 24rpx;
		border-radius: 999rpx;
		font-size: 24rpx;
	}

	/* 退出登录 */
	.logout-section {
		padding: 0 32rpx;
		margin-top: 24rpx;
	}

	.logout-btn {
		width: 100%;
		background-color: #FF3B30;
		color: #FFFFFF;
		border: none;
		border-radius: 999rpx;
		padding: 24rpx;
		font-size: 28rpx;
		font-weight: bold;
	}
</style>